<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>A2A CHAT</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body onload="setTimeout(init,500);">
<h2>A2A Chat</h2>
<form action="javascript:nameMe(document.getElementById('meNickname').value)">
<h3>You are:&nbsp;&nbsp;&nbsp;<input type="text" id="meNickname" value="guest">
<input type="submit" value="Set nickname!">
</h3></form>
<h3><form action="javascript:postMessage()">
You say:&nbsp;&nbsp;&nbsp;<input type="text" id="messageBody" value="Hello world!">
<input type="submit" value="Shout!">
</h3></form>
<h3>You hear:&nbsp;&nbsp;&nbsp;<button onclick="document.getElementById('trace').innerHTML='';">clear</button></h3>
<pre id='trace' style="border:2px solid black;background:#EFE;"></pre>

<script type="text/javascript" src='/hbc/myPrototype.js'></script>
<script type="text/javascript" src='/hbc/hbc.js'></script>
<script type="text/javascript" src='/hbc/jsonize.js'></script>
<script type="text/javascript" src='/hbc/pubsubAgent.js'></script>
<script type="text/javascript" src='/hbc/busAgent.js'></script>
<script type="text/javascript" src='/hbc/autobus.js'></script>
<script type="text/javascript" src='/hbc/cookies.js'></script>
<script type="text/javascript">
function puts(msg) {
  var t = document.getElementById("trace");
  t.innerHTML = t.innerHTML.replace(/^/, msg + "\n");
}

var autobus = new Autobus("a2ac");

if(1)
autobus.hbc.logCB = function(msg) {
  puts("logCB: " + msg) ;
}

function log(msg) {
//   return;
   puts(msg);
}

var pingsLog = {};
function onIntendeePing(variable, value) {
    pingsLog[this.name] = this;
    log("intendee " + this.name + " heard at " + new Date());
    if (me.ping < value) me.ping = value;
}

function onIntendeeNickname(variable, value) {
    puts("intendee " + this.name + " nickname is " + value);
    if (this === me) {
      cookies.set("a2ac_nick", value);
      document.getElementById('meNickname').value = value;
    }
}

function onIntendeesSplice(tag, index, howMany) {
   for (var i = 3; i < arguments.length ; i++) {
      var intendee = arguments[i];
      puts("new intendee id " + intendee.name);
      intendee.subscribe("ping", onIntendeePing);
      intendee.subscribe("nickname", onIntendeeNickname);
   }
}


function onMessageContent(variable, value) {
    var intendee = autobus.tagsonomy.getOr(this.from, null);
    var who = (intendee && intendee.nickname ? intendee.nickname : "intendee " + this.intendee);

    puts(who + " said: " + value);
}

function onMessageTimestamp(variable, value) {
    if (me.ping < value) me.ping = value;
}

var messagesQueue = [];

function onMessagesSplice(tag, index, howMany) {
   for (var i = 3; i < arguments.length ; i++) {
     var message = arguments[i];

     log("new message " + message.name);
     message.subscribe("content", onMessageContent);
     message.subscribe("timestamp", onMessageTimestamp);
     messagesQueue.unshift(message);
     var removed = messagesQueue.splice(10,10);
     for (var lst = removed, l = lst.length, j = l - 1; j >= 0; j--) {
        log("message " + lst[j].name + " forgotten");
        lst[j].forget();
     }
   }
}
var me;

function postMessage() {
  var v = document.getElementById('messageBody');
  var msg = new BusAgent(autobus, agentUUID("m"), BusAgent.prototype.here);
  msg.sets({
    tags: ["message"],
    from: me.name,
    //to: otherIntendee,
    content: v.value,
    timestamp: 1 + me.ping
  });
  v.value = "";
}

function nameMe(name) {
   me.set("nickname", name);
}

function pingMe() {
   me.set("ping", 1 + me.ping);
}

var lastPingsLog = {};
function cleanGone() {
  for (var lst = autobus.tagsonomy.getOr("intendee",[]), l = lst.length, i = l - 1; i >= 0; i--) {
     var intendee=lst[i];
     if (intendee === me || pingsLog[intendee.name] || lastPingsLog[intendee.name])
        continue; // intendee still here

     // intendee is gone
     puts("intendee " + intendee.name + " is gone!");
     intendee.forget();
   }

   lastPingsLog = pingsLog;
   pingsLog = {};
}

function autoConfig() {
  var nick = cookies.get("a2ac_nick");
  if (!nick) {
    var names = [];
    var intendees = autobus.tagsonomy.getOr("intendee",[]);
    for (var l = intendees.length, i = l - 1; i >= 0; i--)
      names.push(intendees[i].nickname);
    
    var lst = [ "red", "blue", "green", "purple", "orange", "pink", "gray" ];
    for (var l = lst.length, i = l - 1; i >= 0; i--) {
       if (names.indexOf(lst[i]) != -1) continue;
       nick = lst[i];
    }   
    if (!nick) {
      var default_prefix = "guest";
      var i = 2;
      while (names.indexOf(default_prefix + i) != -1) i++;
      nick = default_prefix + i;
    }
  }
  me.set("nickname", nick);
}

function init() {
   autobus.init();
   autobus.tagsonomy.subscribe("intendee", onIntendeesSplice);
   autobus.tagsonomy.subscribe("message", onMessagesSplice);

   me = new BusAgent(autobus, agentUUID("i"), BusAgent.prototype.here);
   me.setTags("intendee");
   me.ping = 0;
   pingMe();
   setTimeout(autoConfig, 3 * 1000);
   setInterval(function() { pingMe() }, 60 * 2 * 1000 - 30 * Math.random() * 100);
   setInterval(cleanGone, 60 * 2 * 1000);
   window.onunload = finalize;
}

function finalize(e) {
   me.forget();
}
</script>
</body>
</html>
